<template>
  <div>
    <el-table
      ref="table"
      border
      lazy
      :load="getDeptDatas"
      :data="dataList"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      row-key="id"
      @selection-change="selectionChangeHandler"
    >
      <el-table-column type="selection" />
      <el-table-column label="名称" prop="name" />
      <el-table-column prop="deptSort" label="排序" />
      <el-table-column label="状态" prop="enabled">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" @change="changeEnabled(scope.row, scope.row.enabled)" />
        </template>
      </el-table-column>
      <el-table-column label="创建日期" prop="createTime">
        <template slot-scope="{row}">{{ row.createTime | formatTimeFilter }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130px" fixed="right">
        <template slot-scope="{row}">
          <div>
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(row)" />
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletMenu(row)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Dept :show-dept.sync="showDept" :title="'编辑部门'" :edit-data="editData" @search="$emit('search')" />
  </div>
</template>
<script>
import { edit, getDepts, del } from '@/api/system/dept'
import Dept from './Dept'
export default {
  components: { Dept },
  props: {
    dataList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      editData: {},
      showDept: false,
      selections: []
    }
  },
  methods: {
    edit(v) {
      this.editData = v
      this.showDept = true
    },
    getDeptDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        getDepts(params).then(res => {
          resolve(res.list)
        })
      }, 100)
    },
    selectionChangeHandler(selections) {
      this.selections = selections
    },
    deletMenu(v) {
      this.$confirm(`确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del([v.id]).then(res => {
          this.$message.success('操作成功~')
          this.$emit('search')
        })
      }).catch(() => {
      })
    },
    changeEnabled(data, val) {
      this.$confirm(`此操作将 ${data.enabled ? '启用' : '停用'} ${data.name}部门?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        edit(data).then(res => {
          this.$message.success('操作成功~')
          this.$emit('search')
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
